<template>
  <div class="manage">
    <el-dialog
        :title="operateType === 'add' ? '新增帖子' : '更新帖子'"
        :visible.sync="isShow"
    >
      <common-form
          :formLabel="opertateFormLabel"
          :form="operateForm"
          :inline="true"
          ref="form"
      >
      </common-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
    <div class="manage-header">
      <el-button
          type="primary"
          @click="addUser"
          :style="{ height: '40px', 'margin-top': '-20px' }"
      >+新增</el-button
      >
      <common-form
          :formLabel="formLabel2"
          :form="searchFrom3"
          :inline="true"
          ref="form"
      >
      </common-form>
      <common-form
          :formLabel="formLabel"
          :form="searchFrom1"
          :inline="true"
          ref="form"
      >
        <el-button type="primary" @click="getData">关键字搜索</el-button>
      </common-form>
      <common-form
          :formLabel="formLabel"
          :form="searchFrom2"
          :inline="true"
          ref="form"
      >
        <el-button type="primary" @click="getList">ID查找</el-button>
      </common-form>
    </div>
    <div class="common-table">
      <!-- 帖子数据Table -->
      <el-table :data="tableData" stripe style="width: 100%" height="90%">
        <el-table-column prop="uid" label="发布人"> </el-table-column>
        <el-table-column prop="ttitle" label="标题名"> </el-table-column>
        <el-table-column prop="tcontent" label="内容"> </el-table-column>
        <el-table-column prop="tdelete" label="删除状态"> </el-table-column>
        <el-table-column prop="treleaseDate" label="发布日期">
        </el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleRecover(scope.row)"
                title="恢复"
            >恢复</el-button
            >
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                title="删除"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pager">
        <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageData.limit"
            :current-page="pageData.page"
            @current-change="currentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import CommonForm from "@/components/manager/CommonForm.vue";
import CommonTable from "@/components/manager/CommonTable.vue";
export default {
  name: "tie",
  components: {
    CommonForm,
    CommonTable,
  },
  data() {
    return {
      tableData: [],
      operateType: "add",
      isShow: false,
      opertateFormLabel: [
        {
          model: "tname",
          label: "帖子标题",
          type: "input",
        },
        {
          model: "uid",
          label: "发帖人id",
          type: "input",
        },
        {
          model: "text",
          label: "内容",
          type: "input",
        },
      ],
      operateForm: {
        tname: "",
        uid: "",
        text: "",
      },
      formLabel: [
        {
          model: "keyword",
          label: "",
          type: "input",
        },
      ],
      formLabel2: [
        {
          model: "keyword",
          label: "",
          type: "delete",
        },
      ],
      searchFrom1: {
        keyword: "",
      },
      searchFrom2: {
        keyword: "",
      },
      searchFrom3: {
        keyword: "",
      },
      pageData: {
        page: 1,
        limit: 5,
      },
      total: 0,
    };
  },
  methods: {
    //新增帖子
    confirm() {
      const userData = {
        postTitle: this.operateForm.tname,
        postContent: this.operateForm.text,
        uid: this.operateForm.uid,
      };
      this.$http
          .post("/api/emp/post/create", userData, {
            headers: { token: this.token },
          })
          .then((response) => {
            if (response.data.code === 20000) {
              this.$message.success("帖子新增成功");
              this.isShow = false;
              this.getData();
            } else {
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("新增帖子失败：" + error.message);
          });
    },
    addUser() {
      (this.isShow = true), (this.operateType = "add");
      this.operateForm = {
        tname: "",
        tid: "",
        text: "",
        tdate: "",
        tdelete: "正常",
      };
    },
    // 通过文字模糊查询帖子
    getData() {
      const { page, limit } = this.pageData;
      const keyword = this.searchFrom1.keyword;
      const userdelete = this.searchFrom3.keyword;
      let url = `/api/emp/post/select?key=${keyword}&postdelete=${userdelete}&page=${page}&pageSize=${limit}`;

      this.$http
          .get(url, { headers: { token: this.token } })
          .then((response) => {
            if (response.data.code === 20000) {
              let fetchedData = response.data.data.rows;
              this.total = response.data.data.total;
              this.tableData = fetchedData;
              if (!Array.isArray(fetchedData)) {
                fetchedData = [fetchedData];
              }
              this.tableData = fetchedData.map((item) => ({
                ...item,
                tdelete: item.tdelete === 1 ? "正常" : "禁用",
                tcontent:
                    item.tcontent.length > 100
                        ? item.tcontent.substring(0, 100) + "..."
                        : item.tcontent,
              }));
            } else {
              if (response.data.code === 40100) {
                this.$router.push("/login");
              }
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("获取帖子列表失败：" + error.message);
          });
    },
    //id精确查询
    getList() {
      const tid = this.searchFrom2.keyword;
      let url = `/api/emp/post/select-id`;
      if (tid) {
        url += `?tid=${tid}`;
      }

      this.$http
          .get(url, { headers: { token: this.token } })
          .then((response) => {
            if (response.data.code === 20000) {
              let fetchedData = response.data.data;
              this.total = response.data.data.length;
              this.tableData = [fetchedData];
              if (!Array.isArray(fetchedData)) {
                fetchedData = [fetchedData];
              }
              this.tableData = fetchedData.map((item) => ({
                ...item,
                tdelete: item.tdelete === 1 ? "正常" : "禁用",
                tcontent:
                    item.tcontent.length > 100
                        ? item.tcontent.substring(0, 100) + "..."
                        : item.tcontent,
              }));
            } else {
              if (response.data.code === 40100) {
                this.$router.push("/login");
              }
              this.$message.error(response.data.msg);
            }
          })
          .catch((error) => {
            this.$message.error("获取列表失败：" + error.message);
          });
    },
    //恢复帖子
    handleRecover(index) {
      this.$confirm("此操作将恢复该帖子，是否继续？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const tid = index.tid;
        let url = `/api/emp/post/${tid}`;
        this.$http
            .put(
                url,
                {},
                {
                  headers: { token: this.token },
                }
            )
            .then((response) => {
              if (response.data.code === 20000) {
                this.$message.success("恢复帖子成功");
                this.getData();
              } else {
                if (response.data.code === 40100) {
                  this.$router.push("/login");
                }
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              this.$message.error("恢复失败：" + error.message);
            });
      });
    },
    //删除帖子
    handleDelete(index) {
      this.$confirm("此操作将删除该帖子，是否继续？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const tid = index.tid;
        this.$http
            .delete(`/api/emp/post/${tid}`, {
              headers: { token: this.token },
            })
            .then((response) => {
              if (response.data.code === 20000) {
                this.$message.success("删除帖子成功");
                this.getData();
              } else {
                if (response.data.code === 40100) {
                  this.$router.push("/login");
                }
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              this.$message.error("删除失败：" + error.message);
            });
      });
    },
    currentChange(val) {
      this.pageData.page = val;
      this.getData();
    },
  },
  created() {
    this.token = localStorage.getItem("token");
    if (!this.token) {
      this.$router.push("/login");
    } else {
      this.getData();
    }
  },
};
</script>
<style lang="less" scoped>
.manage {
  height: 100%;

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    height: 90%;
    position: relative;

    .pager {
      position: absolute;
      right: 20px;
      bottom: 0;
    }
  }
}
</style>
